package org.pku_uestc.hackathon;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.pku_uestc.hackathon.bean.ContactHolder;
import org.pku_uestc.hackathon.bean.ContactInfo;
import org.pku_uestc.hackathon.sensor.mobile.CallReceiver;
import org.pku_uestc.hackathon.sensor.mobile.SmsReceiver;
import org.pku_uestc.hackathon.utils.ContactUtils;
import org.pku_uestc.hackathon.utils.DialogToastUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ContactsActivity extends Activity {

	private static final int MESSAGE_GET_CONTACTS_DONE = 1;

	private AutoCompleteTextView mContactInput;
	private Button okBtn;
	private ListView mContactList;
	private ContactAdapter mContactAdapter;
	private ContentAdapter mContentAdapter;
	private Cursor cursor;
	private List<ContactInfo> mList;
	private ProgressDialog mLoadingDialog;
	private CallReceiver mCallReceiver;
	private SmsReceiver mSmsReceiver;
	private String[] phones;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contacts);
		mContactInput = (AutoCompleteTextView) findViewById(R.id.contact_input);
		okBtn = (Button) findViewById(R.id.ok_btn);
		mContactList = (ListView) findViewById(R.id.contacts_list);
		mContactAdapter = new ContactAdapter(getApplicationContext());

		ContentResolver cr = getContentResolver();
		// 制定查询字段
		String[] fieldes = { ContactsContract.Contacts._ID,
				ContactsContract.Contacts.DISPLAY_NAME };
		// 获得查询的信息
		cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, fieldes, null,
				null, null);
		mContentAdapter = new ContentAdapter(getApplicationContext(), cursor);
		mContactInput.setAdapter(mContentAdapter);
		mContactInput.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				cursor.move(position);
				Log.i("huyang",
						cursor.getString(cursor
								.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)));
			}
		});

		mContactList.setAdapter(mContactAdapter);
		mContactList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ContactHolder holder = (ContactHolder) view.getTag();
				holder.check.toggle();
				mContactAdapter.getIsSelected().put(position,
						holder.check.isChecked());
				mList.get(position).setCheck(holder.check.isChecked());
			}
		});
		okBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				getAccessPhoneNumber();
			}
		});
		mLoadingDialog = DialogToastUtils.showProgressDialog(this, getText(R.string.dialog_title), getText(R.string.dialog_msg), false, true);
		mThread.start();
	}

	protected void getAccessPhoneNumber() {
		Log.i("HHH", "getAccessPhoneNumber");
		int size = mList.size();
		int count = 0;
		
		for (int i = 0; i < size; i++) {
			if (mContactAdapter.getIsSelected().get(i))
				Log.i("huyang", mList.get(i).getName() + "  "
						+ mList.get(i).getNumber());
			count++;
		}
		Intent i = new Intent(this, SilentActivity.class);
		i.putExtra("phone", phones);
		setResult(RESULT_OK, i);
		finish();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	
	private Thread mThread = new Thread() {
		@Override
		public void run() {
			mList = ContactUtils.getPhoneContacts(getApplicationContext());
			mHandler.sendEmptyMessage(MESSAGE_GET_CONTACTS_DONE);
		}
	};

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == MESSAGE_GET_CONTACTS_DONE) {
				mContactAdapter.setList(mList);
				mContactAdapter.notifyDataSetChanged();
				mLoadingDialog.dismiss();
			}
		}
	};

	class ContactAdapter extends BaseAdapter {

		private LayoutInflater inflater;
		private List<ContactInfo> list;
		private Map<Integer, Boolean> isSelected;

		public ContactAdapter(Context context) {
			list = new ArrayList<ContactInfo>();
			isSelected = new HashMap<Integer, Boolean>();
			inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ContactHolder holder = null;
			ContactInfo info = list.get(position);
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.contact_item, null);
				holder = new ContactHolder();
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.check = (CheckBox) convertView
						.findViewById(R.id.checkbox);
				convertView.setTag(holder);
			} else {
				holder = (ContactHolder) convertView.getTag();
			}
			holder.name.setText(info.getName());
			holder.check.setChecked(isSelected.get(position));
			return convertView;
		}

		public List<ContactInfo> getList() {
			return list;
		}

		public void setList(List<ContactInfo> list) {
			this.list = list;
			int size = list.size();
			for (int i = 0; i < size; i++) {
				getIsSelected().put(i, false);
			}
		}

		public Map<Integer, Boolean> getIsSelected() {
			return isSelected;
		}

	}

	class ContentAdapter extends CursorAdapter {

		ContentResolver resolver;

		public ContentAdapter(Context context, Cursor c) {
			super(context, c);
			resolver = context.getContentResolver();
		}

		@Override
		// 将信息绑定到控件的方法
		public void bindView(View view, Context context, Cursor cursor) {
			((TextView) view)
					.setText(cursor.getString(cursor
							.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)));

		}

		@Override
		public CharSequence convertToString(Cursor cursor) {
			return cursor
					.getString(cursor
							.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
		}

		@Override
		// 创建自动绑定选项
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			final LayoutInflater inflater = LayoutInflater.from(context);
			final TextView tv = (TextView) inflater.inflate(
					android.R.layout.simple_spinner_dropdown_item, parent,
					false);
			tv.setText(cursor.getString(cursor
					.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)));
			return tv;
		}

	}
}
